#!/usr/bin/with-contenv bashio

# 资源管理相关函数

# 下载文件
download_file() {
    local file_url=$1
    local local_path=$2
    
    if curl -s -f "${file_url}" -o "${local_path}"; then
        bashio::log.info "下载成功: $(basename ${local_path})"
        return 0
    else
        bashio::log.error "下载失败: ${file_url}"
        return 1
    fi
}

# 添加资源到配置
add_resource() {
    local resources_file=$1
    local resource_url=$2
    
    local resource_id=$(cat /proc/sys/kernel/random/uuid | sed 's/-//g')
    local tmp_file=$(mktemp)
    
    if jq --arg id "${resource_id}" \
          --arg url "${resource_url}" \
          '.data.items += [{"id": $id, "url": $url, "type": "module"}]' \
          "${resources_file}" > "${tmp_file}"; then
        mv "${tmp_file}" "${resources_file}"
        bashio::log.info "添加资源: ${resource_url}"
        return 0
    else
        rm -f "${tmp_file}"
        bashio::log.error "添加资源失败: ${resource_url}"
        return 1
    fi
}